const userDao = require('../database/UserDao');
const jwt = require('jsonwebtoken');
const config = require('../config/config');
const authMiddleware = require('../middleware/AuthMiddleWare');
const { success, fail } = require('../utils/response');

const onlineUsers = require('../utils/onlineUsers').getOnlineUsers();
const { getIo } = require('../socket');

const router = require('express').Router();

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const { username, password, realName, companyName, phone } = req.body;
    
    // 检查用户名是否已存在
    const existingUser = await userDao.verifyUserLogin(username, password);
    if (existingUser) {
      return res.status(400).json(fail(4001, '用户名已存在'));
    }
    
    const userId = await userDao.registerUser({
      username,
      password,
      realName,
      userType: 'customer',
      companyName,
      phone
    });
    const io = getIo();
    io.emit('server:user-registered', { username, realName });
    res.status(201).json(success({ message: '注册成功，请等待管理员审核', userId }));
  } catch (error) {
    res.status(500).json(fail(5000, '注册失败'));
  }
});

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    const user = await userDao.verifyUserLogin(username, password);
    
    if (!user) {
      return res.json(fail(5000, '用户名或密码错误'));
    }
    
    if (user.user_type !== 'admin' && !user.is_verified) {
      return res.status(403).json(fail(5000, '账号未审核，请等待管理员审核'));
    }
    
    // 生成JWT令牌
    const token = jwt.sign(
      { userId: user.id, username: user.username, userType: user.user_type },
      config.jwt.secret,
      { expiresIn: config.jwt.expiresIn }
    );
    
    res.json(success({ token, user }));
  } catch (error) {
    res.status(500).json(fail(5000, '登录失败'));
  }
});

// 获取用户列表（管理员权限）
router.get('/list', authMiddleware.isAdmin, async (req, res) => {
  try {
    const users = await userDao.getAllUsers();
    res.json(success(users));
  } catch (error) {
    res.status(500).json(fail(5000, '后端获取用户列表失败'));
  }
});

// 审核用户（管理员权限）
router.put('/:id/verify', authMiddleware.isAdmin, async (req, res) => {
  try {
    const { isVerified } = req.body;
    const result = await userDao.updateUserStatus(req.params.id, isVerified);
    
    if (result) {
      const io = getIo();
      io.emit('server:user-verified', {
        id: req.params.id,
        isVerified
      });
      res.json(success({ message: '用户状态更新成功' }));
    } else {
      res.status(404).json(fail(4000, '用户不存在'));
    }
  } catch (error) {
    res.status(500).json(fail(5000, '更新用户状态失败'));
  }
});

module.exports = router;